import { useEffect, useRef, useState } from 'react';
import { useSearchParams } from 'react-router-dom';

import { useAntdTable } from 'ahooks';
import {
  Button,
  Card,
  Col,
  DatePicker,
  Divider,
  Input,
  Modal,
  Popconfirm,
  Row,
  Select,
  Table,
  Tag,
  Tooltip
} from 'antd';
import dayjs, { Dayjs } from 'dayjs';
import { cloneDeep, pull } from 'lodash-es';

import Filter from '@/components/filter';
import Text from '@/components/text';

import { store } from '@/store';

import { usePermission } from '@/auth';
import { DefectAndWorkTicketStatusObj } from '@/enum/equipment';
import {
  equDefectAcceptanceSubmit,
  equDefectBack,
  equDefectDelete,
  equDefectPage
} from '@/services/bizApi/shebaoquexianjiekou';
import { ProFormSelect } from '@ant-design/pro-form';

import Audit, { AuditRef } from './audit';
import EchartsBar from './echartsBar';
import Edit, { EditRef } from './edit';
import IsPass, { IsPassRef } from './ispass';
import Statistics from './statistics';

/** 该模块增删改查对象 */
export type BizObject = BIZAPI.EquDefectPageResp;

const Page: React.FC = () => {
  const [searchParams] = useSearchParams();
  const equipmentCode = searchParams.get('equipmentCode');
  const permission = usePermission();
  const edit = useRef<EditRef>(null);
  const audit = useRef<AuditRef>(null);
  const isPass = useRef<IsPassRef>(null);
  const [searchData, setSearchData] = useState({});
  const [activeType, setActiveType] = useState('');
  const [visiable, setVisiable] = useState<boolean>(false);
  const [processLogList, setProcessLogList] = useState<BIZAPI.ProcessLogEntity[]>([]);
  const [defectLevelSort, setDefectLevelSort] = useState<string>('');
  const [timeSort, setTimeSort] = useState<string>('');
  const current = useRef<number>(1);
  const [filter] = Filter.useForm();
  const table = useAntdTable(
    async ({ c, pageSize }, { id, dateTime, defectStatusList, ...formData }) => {
      const [beginTime, endTime] = ((dateTime as [Dayjs?, Dayjs?]) || []).map((v) =>
        v?.format('YYYY-MM-DD HH:mm:ss')
      );

      const statusList = cloneDeep(defectStatusList);
      console.log('current.current:', current.current);
      const query = {
        ...formData,
        ...id,
        defectStatusList: !defectStatusList
          ? undefined
          : statusList.includes('待确认')
            ? [10, 11, 12, 13, ...pull(statusList, '待确认')]
            : [...statusList],
        statisticsCondition: activeType,
        beginTime,
        endTime: endTime ? `${dayjs(endTime).format('YYYY-MM-DD')} 23:59:59` : undefined,
        page: current.current,
        size: pageSize
        // timeSort: TimeSort.倒序
      };
      if (defectLevelSort) {
        query.defectLevelSort = defectLevelSort ? defectLevelSort : '';
      } else if (timeSort) {
        query.timeSort = timeSort ? timeSort : '';
      }

      setSearchData(query);
      const res = await equDefectPage(query);
      return {
        list: res.data?.records || [],
        total: res.data?.total || 0
      };
    },
    {
      form: filter
    }
  );

  //点击排序
  const handleChange = (a: any, b: any, c: any) => {
    const { field, order } = c;

    console.log('sorter', a, b, c);

    // console.log(table, table.tableProps);
    current.current = a.current;
    //第一个排序
    if (field == 'defectLevel') {
      if (order == 'ascend') {
        setDefectLevelSort('1');
      } else {
        setDefectLevelSort('0');
      }
      setTimeSort('');
    } else if (field == 'createTime') {
      if (order == 'ascend') {
        setTimeSort('1');
      } else {
        setTimeSort('0');
      }
      //把前一个排序的参数清空掉
      setDefectLevelSort('');
    } else {
      setDefectLevelSort('');
      setTimeSort('');
    }

    table.search.submit();
  };

  const onSearch = () => {
    table.search.submit();
  };

  const onReset = () => {
    table.search.reset();
  };

  useEffect(() => {
    if (equipmentCode) {
      filter?.setFieldsValue({ equipmentCode });
    }
  }, [equipmentCode]);

  const onActiveTypeChange = (type: string) => {
    current.current = 1;
    if (type !== activeType) {
      table.search.reset();
      setActiveType(type);
    } else {
      setActiveType('');
    }
    table.search.submit();
  };

  return (
    <>
      {/**统计 */}
      <Statistics activeType={activeType} onActiveTypeChange={onActiveTypeChange} />

      {/* 筛选 */}
      <Filter
        onFinish={onSearch}
        form={filter}
        extra={
          <>
            {permission.check() &&
              (store?.user?.roles?.includes('xjry') ||
                store?.user?.roles?.includes('scbzz') ||
                store?.user?.roles?.includes('yxry')) && (
                <Button
                  onClick={() => {
                    edit.current?.open({
                      type: 'add',
                      onSuccess: () => {
                        table.refresh();
                      }
                    });
                  }}
                  type="primary"
                >
                  缺陷上报
                </Button>
              )}
          </>
        }
      >
        {/* <Filter.Item name="defectNo">
          <Input
            style={{
              width: 220
            }}
            placeholder="请输入缺陷单号"
          />
        </Filter.Item> */}
        <ProFormSelect
          name="siteList"
          style={{ width: 220 }}
          allowClear
          label=""
          fieldProps={{
            showSearch: true,
            mode: 'multiple',
            maxTagCount: 'responsive'
          }}
          placeholder="请选择站点"
          request={async () => {
            return (store.dict['productionSite'] || []).map((item) => ({
              value: item.dicValue,
              label: item.dicName
            }));
          }}
        />
        <Filter.Item name="equipmentName">
          <Input
            style={{
              width: 220
            }}
            placeholder="请输入设备名称"
          />
        </Filter.Item>
        {/* <Filter.Item name="equipmentCode">
          <Input
            style={{
              width: 220
            }}
            placeholder="请输入设备编号"
          />
        </Filter.Item> */}

        <Filter.Item name="defectLevel">
          <Select
            style={{
              width: 220
            }}
            allowClear
            placeholder="请选择缺陷等级"
            options={[
              {
                label: '一级',
                value: '一级'
              },
              {
                label: '二级',
                value: '二级'
              },
              {
                label: '三级高',
                value: '三级高'
              },
              {
                label: '三级中',
                value: '三级中'
              },
              {
                label: '三级低',
                value: '三级低'
              }
            ]}
          />
        </Filter.Item>
        <Filter.Item name="defectStatusList">
          <Select
            style={{
              width: 220
            }}
            allowClear
            mode="multiple"
            maxTagCount="responsive"
            placeholder="请选择状态"
            options={[
              {
                label: '待确认',
                value: '待确认'
              },
              {
                label: '待审核',
                value: 30
              },
              {
                label: '审核驳回',
                value: 31
              },
              {
                label: '挂起',
                value: 32
              },
              {
                label: '待申请工作票',
                value: 40
              },
              {
                label: '打回',
                value: 44
              },
              {
                label: '待发起验收',
                value: 50
              },
              {
                label: '待验收',
                value: 51
              },
              {
                label: '验收驳回',
                value: 52
              },
              {
                label: '已完成',
                value: 99
              }
            ]}
          />
        </Filter.Item>
        <Filter.Item name="status">
          <Select
            style={{
              width: 220
            }}
            allowClear
            placeholder="请选择完成类型"
            options={[
              {
                label: '未完成',
                value: '0'
              },
              {
                label: '已完成',
                value: '1'
              }
            ]}
          />
        </Filter.Item>
        {/* <Filter.Item name="defectType">
          <Select
            style={{
              width: 220
            }}
            allowClear
            placeholder="请选择缺陷类型"
            options={[
              {
                label: '设备缺陷',
                value: 1
              },
              {
                label: '生产缺陷',
                value: 2
              }
            ]}
          />
        </Filter.Item> */}
        {/* <Filter.Item name="faultTypeList">
          <Select
            style={{
              width: 200
            }}
            allowClear
            showSearch={true}
            optionFilterProp="label"
            mode="multiple"
            maxTagCount="responsive"
            placeholder="故障类型"
            options={[
              {
                label: '设备',
                value: '设备'
              },
              {
                label: '电气',
                value: '电气'
              },
              {
                label: '仪控',
                value: '仪控'
              },
              {
                label: '土建',
                value: '土建'
              },
              {
                label: '车辆',
                value: '车辆'
              }
            ]}
          />
        </Filter.Item> */}
        <Filter.Item name="maintenanceTypeList">
          <Select
            style={{
              width: 220
            }}
            allowClear
            mode="multiple"
            maxTagCount="responsive"
            placeholder="请选择维修类型"
            options={[
              {
                label: '内修',
                value: '内修'
              },
              {
                label: '外修',
                value: '外修'
              },
              {
                label: '挂起',
                value: '挂起'
              }
            ]}
          />
        </Filter.Item>

        {/* <Filter.Item name="createBy">
          <Input
            style={{
              width: 220
            }}
            placeholder="请输入上报人"
          />
        </Filter.Item> */}
        <Filter.Item name="dateTime">
          <DatePicker.RangePicker placeholder={['发现时间', '发现时间']} />
        </Filter.Item>
        <Filter.Item>
          <Button htmlType="submit" disabled={table.loading}>
            搜索
          </Button>
        </Filter.Item>

        <Filter.Item>
          <Button onClick={onReset} disabled={table.loading}>
            重置
          </Button>
        </Filter.Item>
      </Filter>
      {/* end 筛选 */}

      {/* 表格 */}
      <Table<BizObject>
        size="small"
        columns={[
          {
            title: '序号',
            dataIndex: 'index',
            align: 'center',
            render: (_, row, index) => index + 1
          },
          // {
          //   title: '缺陷单号',
          //   dataIndex: 'defectNo',
          //   width: 160
          // },
          {
            title: '站点',
            dataIndex: 'site',
            width: 160
          },
          {
            title: '设备名称',
            dataIndex: 'equipmentName',
            render: (v, row) => {
              return (
                <span
                  style={{
                    color: [30, 31, 32, 40, 50, 51, 52].includes(row.defectStatus!) ? '#bd9b3e' : ''
                  }}
                >
                  {v}
                </span>
              );
            }
          },
          {
            title: '缺陷描述',
            dataIndex: 'defectDescription',
            width: 300,
            ellipsis: true,
            render: (text) => (
              <Tooltip placement="top" title={text} arrow={true}>
                <div
                  style={{
                    width: '300px',
                    wordBreak: 'break-all',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    whiteSpace: 'nowrap'
                  }}
                >
                  {text}
                </div>
              </Tooltip>
            )
          },
          // {
          //   title: '设备编号',
          //   dataIndex: 'equipmentCode'
          // },
          // {
          //   title: '缺陷类型',
          //   dataIndex: 'defectType',
          //   render: (text) => (text === 1 ? '设备缺陷' : '生产缺陷')
          // },
          {
            title: '缺陷等级',
            dataIndex: 'defectLevel',
            sorter: true
          },
          // {
          //   title: '故障类型',
          //   dataIndex: 'faultType'
          // },
          {
            title: '维修类型',
            dataIndex: 'maintenanceType'
          },
          {
            title: '发现时间',
            dataIndex: 'createTime',
            sorter: true,
            render: (text) => (text ? dayjs(text).format('YYYY-MM-DD') : '')
          },
          {
            title: '计划时间',
            dataIndex: 'maintenancePlanBeginTime',
            render: (text) => (text ? dayjs(text).format('YYYY-MM-DD') : '')
          },
          {
            title: '上报人',
            dataIndex: 'createBy'
          },
          {
            title: '状态',
            dataIndex: 'statusShow',
            render: (v) => {
              const item = v.replace(/\(/g, '').replace(/\)/g, '');
              const obj = DefectAndWorkTicketStatusObj.get(item);
              if (obj) {
                return <Tag color={obj.color}>{obj.text}</Tag>;
              } else {
                return <span>{v}</span>;
              }
            }
          },
          {
            title: '当前处理人',
            dataIndex: 'nextTargetList',
            render: (text, row) =>
              row?.nextTargetList?.map((item) => item?.nextOptTargetName)?.join('/')
          },
          // {
          //   title: '维修备注',
          //   dataIndex: 'maintenanceRemark'
          // },
          {
            title: '操作',
            fixed: 'right',
            align: 'center',
            render: (_, row) => {
              let bool = false;
              row?.nextTargetList?.forEach((item) => {
                if (item?.nextOptTargetType === 1 && store?.user?.id === item?.nextOptTargetId) {
                  bool = true;
                }
                if (
                  item?.nextOptTargetType === 2 &&
                  store?.user?.roleIds?.includes(item?.nextOptTargetId as unknown as number)
                ) {
                  bool = true;
                }
              });
              return (
                <Text.Space>
                  {permission.check() &&
                    bool &&
                    (row?.defectStatus === 10 ||
                      row?.defectStatus === 32 ||
                      row?.defectStatus === 44) && (
                      <Text
                        onClick={() => {
                          edit.current?.open({
                            type: 'edit',
                            rowData: row,
                            onSuccess: () => {
                              table.refresh();
                            }
                          });
                        }}
                        type="primary"
                      >
                        确认
                      </Text>
                    )}
                  {permission.check() && bool && row?.defectStatus === 11 && (
                    <Text
                      onClick={() => {
                        edit.current?.open({
                          type: 'edit',
                          rowData: row,
                          onSuccess: () => {
                            table.refresh();
                          }
                        });
                      }}
                      type="primary"
                    >
                      确认
                    </Text>
                  )}
                  {permission.check() &&
                    bool &&
                    (row?.defectStatus === 12 || row?.defectStatus === 31) && (
                      <Text
                        onClick={() => {
                          edit.current?.open({
                            type: 'edit',
                            rowData: row,
                            onSuccess: () => {
                              table.refresh();
                            }
                          });
                        }}
                        type="primary"
                      >
                        确认
                      </Text>
                    )}
                  {permission.check() && bool && row?.defectStatus === 13 && (
                    <Text
                      onClick={() => {
                        edit.current?.open({
                          type: 'edit',
                          rowData: row,
                          onSuccess: () => {
                            table.refresh();
                          }
                        });
                      }}
                      type="primary"
                    >
                      确认
                    </Text>
                  )}
                  {permission.check() && bool && row?.defectStatus === 30 && (
                    <Text
                      onClick={() => {
                        audit.current?.open({
                          rowData: row,
                          onSuccess: () => {
                            table.refresh();
                          }
                        });
                      }}
                      type="primary"
                    >
                      审核
                    </Text>
                  )}
                  {permission.check() && bool && row?.defectStatus === 50 && (
                    <>
                      <Popconfirm
                        title={`确定发起验收吗？`}
                        onConfirm={async () => {
                          const res = await equDefectAcceptanceSubmit({
                            id: row.id as unknown as string
                          });

                          store.app?.message.success(res.message);
                          table.refresh();

                          return res.success;
                        }}
                      >
                        <Text>发起验收</Text>
                      </Popconfirm>
                      <Divider type="vertical" />
                      <Popconfirm
                        title={`确定打回吗？`}
                        onConfirm={async () => {
                          const res = await equDefectBack({
                            id: row.id as unknown as string
                          });

                          store.app?.message.success(res.message);
                          table.refresh();

                          return res.success;
                        }}
                      >
                        <Text>打回</Text>
                      </Popconfirm>
                    </>
                  )}
                  {permission.check() && bool && row?.defectStatus === 51 && (
                    <Text
                      onClick={() => {
                        isPass.current?.open({
                          rowData: row,
                          onSuccess: () => {
                            table.refresh();
                          }
                        });
                      }}
                      type="primary"
                    >
                      验收
                    </Text>
                  )}
                  {permission.check() && (
                    <Text
                      onClick={() => {
                        edit.current?.open({
                          type: 'detail',
                          rowData: row,
                          onSuccess: () => {
                            table.refresh();
                          }
                        });
                      }}
                      type="primary"
                    >
                      详情
                    </Text>
                  )}
                  {permission.check() && (
                    <Text
                      onClick={() => {
                        setVisiable(true);
                        setProcessLogList(row?.processLogList || []);
                      }}
                      type="primary"
                    >
                      流程日志
                    </Text>
                  )}
                  {permission.check() &&
                    (store?.user?.roles?.includes('sbgcs') ||
                      store?.user?.roles?.includes('dqgcs') ||
                      store?.user?.roles?.includes('ykgcs') ||
                      store?.user?.roles?.includes('tjgcs') ||
                      store?.user?.roles?.includes('clgcs')) && (
                      <Popconfirm
                        title={
                          <div>
                            <div style={{ color: 'red' }}>此操作会删除关联的工作票！</div>
                            确定删除吗？
                          </div>
                        }
                        onConfirm={async () => {
                          const res = await equDefectDelete({
                            id: row.id as unknown as string
                          });

                          store.app?.message.success(res.message);
                          table.refresh();

                          return res.success;
                        }}
                      >
                        <Text type="danger">删除</Text>
                      </Popconfirm>
                    )}
                </Text.Space>
              );
            }
          }
        ]}
        scroll={{
          x: 'max-content'
        }}
        rowKey="id"
        bordered
        {...table.tableProps}
        onChange={handleChange}
        pagination={{
          ...table.tableProps.pagination,
          current: current.current,
          showTotal: (total) => `共 ${total} 条`,
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '50', '100']
        }}
      />
      {/* 图表 */}
      <Row>
        <Col span={12}>
          <Card title="缺陷等级统计" style={{ width: '100%', height: '400px' }}>
            <EchartsBar searchData={searchData} type="level" />
          </Card>
        </Col>
        <Col span={12}>
          <Card title="缺陷状态统计" style={{ width: '100%', height: '400px' }}>
            <EchartsBar searchData={searchData} type="status" />
          </Card>
        </Col>
      </Row>
      {/* end表格 */}

      <Edit ref={edit} />
      <Audit ref={audit} />
      <IsPass ref={isPass} />
      <Modal
        width={1000}
        title="流程日志"
        open={visiable}
        footer={null}
        onCancel={() => {
          setVisiable(false);
          setProcessLogList([]);
        }}
      >
        <Table
          columns={[
            {
              title: '状态',
              dataIndex: 'dataStatus'
            },
            {
              title: '操作',
              dataIndex: 'description'
            },
            {
              title: '操作人',
              dataIndex: 'optUserName'
            },
            {
              title: '操作时间',
              dataIndex: 'optTime'
            },
            {
              title: '备注',
              dataIndex: 'remark'
            }
          ]}
          dataSource={processLogList}
        />
      </Modal>
    </>
  );
};

export default Page;
